import fs from 'fs';
import path from 'path';
import { dayjs } from 'element-plus';
import dltConfig from './lib/dltconfig.js';
import ssqConfig from './lib/ssqconfig.js';

/**
 * 定时任务
 * 大乐透开奖时间：每周一、三、六 21:25 开奖
 * 双色球开奖时间：每周二、四、日 21：15 开奖
 * 每天 21:30 执行一次 30 21 * * * php /www/wwwroot/lucklottery/dist/task.php
 * @version 1.0.0
 */
class TaskController {
    dataRoot = '';
    logFilename = '';
    constructor() {
        this.dataRoot = path.dirname(__dirname) + '/data';
        this.logFilename = this.dataRoot + '/log/task/' + dayjs().format('YYYYMM') + '.log';
        if (!fs.existsSync(path.dirname(this.logFilename))) {
            fs.mkdirSync(path.dirname(this.logFilename), true);
        }
    }

    run(weekday = '') {
        if (!weekday) {
            weekday = new Date().getDay();
        }
        // weekday = 2;
        let weekdayName = ['天', '一', '二', '三', '四', '五', '六'][weekday];
        if (weekday == 5) {
            savelog(this.logFilename, '星期' + weekdayName + ' 不执行');
            return;
        }

        let isDlt = weekday == 1 || weekday == 3 || weekday == 6;
        let isSsq = weekday == 2 || weekday == 4 || weekday == 0;
        let moduleName = isDlt ? 'dlt' : 'ssq';
        let moduleDir = this.dataRoot + '/' + moduleName + '/';
        let moduleOrderDir = moduleDir + 'order/';

        // 1. 采集数据
        // savelog(this->logFilename, '1. 采集数据');
        if (isDlt) {
            message = fetchDlt();
        }
        if (isSsq) {
            message = fetchSsq();
        }
        if (message['code'] !== 200) {
            savelog(this.logFilename, '1. 采集数据失败：' + message['message']);
            return;
        }
        savelog(this.logFilename, '1. 采集数据成功：' + message['message']);
        // 2. 解析数据
        savelog(this.logFilename, '2. 解析数据');
        data = json_decode(file_get_contents(moduleDir + 'data.json'), true);
        // columns = parseColumns(array_map((item) {
        //     return item['lotteryDrawResult'];
        // }, data));
        file_put_contents(moduleDir + 'columns.json', json_encode(columns, JSON_UNESCAPED_UNICODE));
        currentRecord = data[0];
        currentIssue = intval(currentRecord['lotteryDrawNum']);
        nextIssue = currentIssue + 1;
        // 3. 生成号码
        savelog(this.logFilename, '3. 生成号码');
        columns = filteColumns(columns, 3);
        orders = generateOrders(columns, 10, explode(' ', currentRecord['lotteryDrawResult']));
        columns = parseColumns(orders);
        betterOrders = generateOrders(columns, 10, explode(' ', currentRecord['lotteryDrawResult']));
        // 4. 存储下期订单数据
        savelog(this.logFilename, '4. 存储下期订单数据');
        filename = moduleOrderDir + nextIssue + '.json';
        if (file_exists(filename)) {
            nextIssueData = json_decode(file_get_contents(filename), true);
            nextIssueData['AutoList'] = orders;
            nextIssueData['BetterAutoList'] = betterOrders;
        } else {
            nextIssueData = {
                'DrawalInfo_Prev': {
                    'lotteryDrawNum': currentIssue,
                    'lotteryDrawResult': currentRecord['lotteryDrawResult'],
                    'lotteryDrawTime': currentRecord['lotteryDrawTime'],
                },
                'DrawalInfo': {
                    'lotteryDrawNum': nextIssue,
                    'lotteryDrawResult': '',
                    'lotteryDrawTime': '',
                },
                'AiList': {
                    'Nami': [],
                    'DeepSeek': [],
                },
                'AutoList': orders,
                'BetterAutoList': betterOrders,
            };
        }
        file_put_contents(filename, json_encode(nextIssueData, JSON_UNESCAPED_UNICODE));
        // 5. 核对本期开奖结果
        savelog(this.logFilename, '5. 核对本期开奖结果');
        filename = moduleOrderDir.currentIssue + '.json';
        if (file_exists(filename)) {
            splitIndex = isDlt ? 5 : 6;
            prizeList = isDlt ? dltConfig['prize_info'] : ssqConfig['prize_info'];
            currentIssueData = json_decode(file_get_contents(filename), true);
            currentIssueData['DrawalInfo']['lotteryDrawResult'] = currentRecord['lotteryDrawResult'];
            currentIssueData['DrawalInfo']['lotteryDrawTime'] = currentRecord['lotteryDrawTime'];
            currentIssueData['_AutoList'] = calcOrders(currentRecord['lotteryDrawResult'], currentIssueData['AutoList'], splitIndex, prizeList);
            currentIssueData['_BetterAutoList'] = calcOrders(currentRecord['lotteryDrawResult'], currentIssueData['BetterAutoList'], splitIndex, prizeList);
            prizeList = array_filter(currentIssueData['_AutoList'], (row) {
                return row['prizeData']['value'] > 0;
            });
            prizeList = array_merge(prizeList, array_filter(currentIssueData['_BetterAutoList'], (row) {
                return row['prizeData']['value'] > 0;
            }));
            maxRow = [];
            maxValue = 0;
            prizeList.forEach(row => {
                if (row['prizeData']['value'] > maxValue) {
                    maxValue = row['prizeData']['value'];
                    maxRow = row['prizeData'];
                }
            })
            currentIssueData['prizeInfo'] = {
                'list': prizeList,
                'highest': maxRow,
            };
            savelog(this.logFilename, '最高奖项 ' + json_encode(maxRow, JSON_UNESCAPED_UNICODE));
            file_put_contents(filename, json_encode(currentIssueData, JSON_UNESCAPED_UNICODE));
        } else {
            savelog(this.logFilename, '本期 ' + currentIssue + ' 没有订单记录，无需核对。');
        }
        // 6. 生成报告并通知
        savelog(this.logFilename, '星期' + weekdayName + ' 定时任务运行成功。');
    }
}


export default TaskController;